package pack.model;

import java.util.ArrayList;

import pack.help.Command;
import pack.help.State;
import gui.Simulator;


public class Animator implements Runnable{

	// This is the command which this thread is going to execute
	private Command cmd;
	// Remaining time of the current command in milisec
	private int timeRemain;
	// Reference to the robot which this thread is animating
	private ArrayList<Robot> robots;
	// The ideal robot
	private Robot idealRobot;
	// Reference to the simulator to call paint
	private Simulator simulator;
	
	// 40ms = 25fps 
	// this is the period length
	int period = 40;
	
	public Animator(Command c, ArrayList<Robot> robots, Robot idealRobot, Simulator s){
		cmd = c;
		timeRemain = c.getTime();
		this.robots = robots;
		this.idealRobot = idealRobot;
		simulator = s;
	}
	
	public void run(){
		
		
		while(timeRemain > 0){
			if (timeRemain > (period-1) ){
				try {
					
					timeRemain-= period;
					Thread.sleep(period);
					this.moveRobots(period);
					
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				try {
					Thread.sleep(timeRemain);
					this.moveRobots(timeRemain);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				timeRemain=0;
			}
			simulator.repaint();
		}
	}
	
	private void moveRobots(int t){
		idealRobot.stateToParams(new State(idealRobot.idealMove(t,cmd.getV1(),cmd.getV2())));
		State goal = idealRobot.getState();
		for (Robot rob:robots){
			rob.move(t,goal);
		}
	}
	
}
